# -*- coding: utf-8 -*-

import pytest
import base64

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService
from appium.webdriver.clipboard_content_type import ClipboardContentType

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None, appium_host = APPIUM_HOST, appium_port = APPIUM_PORT):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{appium_host}:{appium_port}', options=options)


def test_set_clipboard(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    data = "hello appium"
    driver.set_clipboard(data.encode('utf-8')) # 注意要将string类型转换成bytes类型
    
    driver.quit()


def test_get_clipboard(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    data = "hello android"
    driver.set_clipboard_text(data) # 类型是string
    content_bytes = driver.get_clipboard(ClipboardContentType.PLAINTEXT)
    assert content_bytes.decode('UTF-8') == data
    assert driver.get_clipboard_text() == data
    
    driver.quit()